package com.cdy.jxc_project.utils;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdy.jxc_project.domain.TAdmin;
import com.cdy.jxc_project.service.TAdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/*
 * @Project:jxc_project
 * @Author:cdy(缘生)
 * @Motto:放下杂念,只为迎接明天更好的自己
 * @Date:2023/4/24 16:49
 * */
public class MysqlRealm extends AuthorizingRealm {

    @Resource
    private TAdminService tAdminService;

    //权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证控制流程");
    //判断用户信息是否正确
    // authenticationToken 就是subject.login传递过来的toke
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)
                authenticationToken;
        String userName = usernamePasswordToken.getUsername();//获取用户名
        QueryWrapper<TAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        TAdmin tAdmin = tAdminService.getOne(queryWrapper);
        if (ObjectUtil.hasNull(tAdmin)) {
            return null;
        }
        System.out.println(getName());
        SimpleAuthenticationInfo authenticationInfo = new
                SimpleAuthenticationInfo(tAdmin.getUsername(), tAdmin.getPassword(),
                ByteSource.Util.bytes(tAdmin.getSlot()),getName());
        SecurityUtils.getSubject().getSession().setAttribute(SessionKey.adminKey,tAdmin);
        return authenticationInfo;
    }
}
